package com.margo.project.http;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class MultipartEntityBuilderClient{

	public static void main(String[] args) {
		String url="http://localhost:8080/iep/mobile/mobileservice/fileAction/multipartFile.iep";
		HttpClient client=HttpClients.createDefault();// 开启一个客户端 HTTP 请求 
		HttpPost post = new HttpPost(url);//创建 HTTP POST 请求  
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setCharset(Charset.forName("utf-8"));//设置请求的编码格式
		builder.setMode(HttpMultipartMode.RFC6532);//	
		System.out.println(MultipartEntityBuilderClient.class.getResource("/file/socket.txt"));
		try {
			URI uri = MultipartEntityBuilderClient.class.getResource("/file/socket.txt").toURI();
			File file=new File(uri);
			builder.addBinaryBody("file", file);
			//中文乱码
			//builder.addTextBody("method", "margo");//设置请求参数
			ContentType contentType = ContentType.create("text/plain", "utf-8");
			StringBody stringBody = new StringBody("我喜欢芒果",contentType);
			builder.addPart("method", stringBody);
			
			HttpEntity entity = builder.build();// 生成 HTTP POST 实体  	
			post.setEntity(entity);//设置请求参数
			
			HttpResponse response = client.execute(post);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
				System.out.println(jsonString);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 发起请求 并返回请求的响应
	}
}
